package com.reader.api.thirdplatform.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.reader.api.constants.SmsTemplateEnum;
import com.reader.api.thirdplatform.AliSmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author liujianqing
 * @date 2018/10/24
 */
@Service
public class AliSmsServiceImpl implements AliSmsService {
    private static final Logger logger = LoggerFactory.getLogger(AliSmsServiceImpl.class);
    @Autowired
    private IAcsClient acsClient;

    @Override
    public boolean sendSmsCode(String mobile, SmsTemplateEnum smsTemplateEnum, JSONObject contentJson) {
        Assert.hasLength(mobile,"手机号非法");
        Assert.notNull(smsTemplateEnum,"短信模板不能为null");
        Assert.notNull(contentJson,"短信内容不能为null");

        try {
            SendSmsRequest request = new SendSmsRequest();
            request.setMethod(MethodType.POST);
            request.setPhoneNumbers(mobile);
            request.setSignName("读者");
            request.setTemplateCode(smsTemplateEnum.getCode());
            request.setTemplateParam(contentJson.toJSONString());

            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                return true;
            }
        } catch (Exception e) {
            logger.error("AliSmsServiceImpl#send sms code error！mobile->{} contentJson->{} smsDesc->{}",
                    mobile, contentJson.toJSONString(), smsTemplateEnum.getDesc());
        }
        return false;
    }
}
